<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { ref, reactive } from 'vue'
import { ElTree, ElDivider, ElScrollbar, ElMessageBox, ElMessage } from 'element-plus'

import { useTable } from '@/hooks/web/useTable'
import Write from './components/Write.vue'
import Detail from './components/Detail.vue'
import { Dialog } from '@/components/Dialog'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'

import { generateTree } from './api'
import type { TreeNode } from './api'

import {
  reqClassificationTree,
  reqSmallInstance,
  reqUnbindingDepartment,
  reqDownloadFile
} from '@/api/classify'
import {
  ClassificationTreeResponseData,
  SmallInstanceResponseData,
  SmallInstanceInfo
} from '@/api/classify/type'

import { onMounted } from 'vue'
import type Node from 'element-plus/es/components/tree/src/model/node'
// import { departmentMap } from '../../../public/department'
import { inject } from 'vue'
import { unref } from 'vue'

import { useUserStore } from '@/store/modules/user'

const { t } = useI18n()

const  departmentMap  = inject<any>('departmentMap')

const userStore = useUserStore()

const currentClassification = ref('301000')

const { tableRegister, tableState, tableMethods } = useTable({
  immediate: false,
  fetchDataApi: async () => {
    const res: SmallInstanceResponseData = await reqSmallInstance(
      currentClassification.value,
      currentPage.value,
      pageSize.value
    )
    return {
      list: res.data.list || [],
      total: res.data.total || 0
    }
  }
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList } = tableMethods

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'index',
    label: t('userDemo.index'),
    align: 'center',
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'index',
    }
  },
  {
    field: 'classificationCode',
    label: '分类代码',
    align: 'center',
    table: {
      width: 100
    }

  },
  {
    field: 'classificationName',
    label: '分类名称',
    align: 'center',
    table: {
      width: 200
    }
  },
  {
    field: 'parentName',
    label: '所属中类',
    align: 'center',
    search: {
      hidden: true
    },
    table: {
      width: 150
    }
  },
  {
    field: 'department',
    label: '责任单位',
    align: 'center',
    table: {
      formatter: (row: any) => departmentMap[row.department] || '暂未绑定责任单位',
    }
  },
  {
    field: 'action',
    label: t('tableDemo.action'),
    align: 'center',
    search: { hidden: true },
    form: { hidden: true },
    table: {
      width: 250,
      fixed: 'right',
      slots: {
        default: (data: any) => (
          <>
            <BaseButton type="primary" onClick={() => checkInfo(data.row)}>
              详情
            </BaseButton>
            <BaseButton
              v-show={data.row.isInstanced && userStore.userInfo!.role === 'admin'}
              type="danger"
              onClick={() => unbindDepartment(data.row)}
            >
              解绑责任单位
            </BaseButton>
            <BaseButton
              v-show={!data.row.isInstanced && userStore.userInfo!.role === 'admin'}
              type="success"
              onClick={() => bindDepartment(data.row)}
            >
              绑定责任单位
            </BaseButton>
          </>
        )
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const treeEl = ref<InstanceType<typeof ElTree>>()

const classifyList = ref<any[]>([])

const downloadClassification = () => {
  reqDownloadFile().then((res) => {
    const excel = res
    const downloadUrl = window.URL.createObjectURL(
      new Blob([excel!], { type: 'application/vnd.ms-excel' })
    )

    const a = document.createElement('a')
    a.style.display = 'none'
    a.href = downloadUrl
    a.download = '武穴市编码赋码分类与责任主体清单.xlsx'
    const event = new MouseEvent('click')
    a.dispatchEvent(event)
  })
}
const getClassifyList = async () => {
  const res: ClassificationTreeResponseData = await reqClassificationTree()
  classifyList.value = await generateTree(res.data)
  getList()
}

const renderContent = (
  h,
  {
    node,
    data
  }: {
    node: Node
    data: TreeNode
    store: Node['store']
  }
) => {
  return h(
    'span',
    {
      class: 'custom-tree-node'
    },
    h('span', null, node.label),
    h(
      'span',
      null,
      h(
        'span',
        {
          style: 'color: #909399'
        },
        '（'
      ),
      h(
        'span',
        {
          style: 'color:#f56c6c'
        },
        data.instancedCount
      ),
      h('span', {}, '/'),
      h(
        'span',
        {
          style: 'color: #409eff'
        },
        data.totalCount
      ),
      h(
        'span',
        {
          style: 'color: #909399'
        },
        '）'
      )
    )
  )
}

const nodeClick = (data: any, _node: any) => {
  if (data.type !== 0) {
    currentClassification.value = unref(treeEl)!.getCurrentNode().id
    currentPage.value = 1
    pageSize.value = 10
    getList()
  }
}

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref<SmallInstanceInfo>()
const actionType = ref('')

const checkInfo = (row: SmallInstanceInfo) => {
  currentRow.value = row
  dialogVisible.value = true
  actionType.value = 'detail'
  dialogTitle.value = '实体分类详情'
}
const unbindDepartment = (row: SmallInstanceInfo) => {
  ElMessageBox.confirm('当前责任单位将与该实体分类解绑，请确认是否解绑?', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      reqUnbindingDepartment(row.classificationCode).then((res) => {
        if (res) {
          ElMessage({
            type: 'success',
            message: '解绑成功'
          })
          getClassifyList().then(() => {
            unref(treeEl)!.setCurrentKey(currentClassification.value)
          })
        } else {
          ElMessage({
            type: 'error',
            message: '解绑失败'
          })
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消注销'
      })
    })
}

const bindDepartment = (row: SmallInstanceInfo) => {
  currentRow.value = row
  dialogVisible.value = true
  actionType.value = 'binding'
  dialogTitle.value = '绑定责任单位'
}

const writeRef = ref<ComponentRef<typeof Write>>()

const closeDialog = () => {
  dialogVisible.value = false
  setTimeout(() => {
    getClassifyList().then(() => {
      unref(treeEl)!.setCurrentKey(currentClassification.value)
    })
  }, 1000)
}

const upload = () => {
  writeRef.value!.submitBinding()
}

const AddAction = () => {
  ElMessage.error('黄冈市暂未开放权限，请持续关注相关政策')
}

const delData = () => {
  ElMessage.error('黄冈市暂未开放权限，请持续关注相关政策')
}
onMounted(async () => {
  await getClassifyList()
  unref(treeEl)!.setCurrentKey(currentClassification.value)
})
</script>

<style lang="scss">
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>

<template>
  <div class="flex w-100% h-100%">
    <ContentWrap class="w-320px">
      <div class="flex justify-center items-center">
        <div class="flex-1">实体分类目录</div>
        <BaseButton type="success" @click="downloadClassification">下载目录</BaseButton>
      </div>
      <ElDivider />
      <!-- :default-expanded-keys="['300000']" -->
      <ElScrollbar height="600px">
        <ElTree ref="treeEl" :data="classifyList" node-key="id" :check-on-click-node="true" :props="{
          label: 'label',
          children: 'children'
        }" @node-click="nodeClick" :render-content="renderContent">
          <template #default="{ data }">
            <div :title="data.label" class="whitespace-nowrap overflow-ellipsis overflow-hidden" :style="{
          fontWeight: !data.type ? 'bold' : ''
        }">
              {{ data.label }}
            </div>
          </template>
        </ElTree>
      </ElScrollbar>
    </ContentWrap>
    <ContentWrap class="flex-[3] ml-20px">
      <div class="mb-10px">
        <BaseButton type="primary" @click="AddAction">{{ t('exampleDemo.add') }}</BaseButton>
        <BaseButton type="danger" @click="delData()">
          {{ t('exampleDemo.del') }}
        </BaseButton>
      </div>
      <Table headerAlign="center" v-model:current-page="currentPage" v-model:page-size="pageSize"
        :columns="allSchemas.tableColumns" :data="dataList" :loading="loading" @register="tableRegister" :pagination="{
          total
        }" />
    </ContentWrap>

    <Dialog v-model="dialogVisible" :title="dialogTitle" :width="actionType == 'detail' ? 600 : 500">
      <Write v-if="actionType !== 'detail'" ref="writeRef" :departments="departmentMap" @close-dialog="closeDialog"
        :current-row="currentRow!" />

      <Detail v-if="actionType === 'detail'" :current-row="currentRow" />

      <template #footer>
        <BaseButton v-if="actionType !== 'detail'" type="primary" @click="upload">
          确认绑定
        </BaseButton>
        <BaseButton @click="closeDialog">{{
          actionType !== 'detail' ? '取消' : '返回'
        }}</BaseButton>
      </template>
    </Dialog>
  </div>
</template>
